package 代码随想录.数组.螺旋矩阵顺时针;

import com.sun.glass.ui.Size;

import java.util.Arrays;
import java.util.LinkedList;

/**剑指 Offer 29. 顺时针打印矩阵
 * todo:这里写成逆时针打印了，但是检查了一下是没有错的，符合逆时针打印矩阵
 * link:https://leetcode-cn.com/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/
 * @author ChenweiLin
 * @create 2021-12-01 21:37
 */
public class shunShiZhenDaYinJuZhenIcof {
    public static void main(String[] args) {
        int[] ints = spiralOrder(new int[][]{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}});
        for (int anInt : ints) {
            System.out.println(anInt);
        }

    }
    public static int[] spiralOrder(int[][] matrix) {
        //模拟过程
        int startRow = 0;//初始的行
        int startColumn = 0;//初始的列
        int totalSize = matrix.length*matrix[0].length;//总数
        int loopCount = 0;//圈数
        int row = matrix.length;//行数
        int column = matrix[0].length;//列数
        int[] result = new int[totalSize];//结果数组
        int index = 0;//数组下标


        while (totalSize > 0 && startRow != row/2){
            loopCount++;
            //顺时针
            //左边
            for (; startRow < row-loopCount && totalSize > 0; startRow++,totalSize--,index++) {
                result[index] = matrix[startRow][startColumn];
            }
            //下边
            for (; startColumn < column-loopCount && totalSize > 0; startColumn++,totalSize--,index++) {
                result[index] = matrix[startRow][startColumn];
            }
            //右边
            for (; startRow >= loopCount && totalSize > 0; startRow--,totalSize--,index++) {
                result[index] = matrix[startRow][startColumn];
            }
            //上边
            for (; startColumn >= loopCount && totalSize > 0; startColumn--,totalSize--,index++) {
                result[index] = matrix[startRow][startColumn];
            }

            //一圈结束
            startRow++;
            startColumn++;

        }
        //如果行是奇数 读取内部的最后一行
        if (row % 2== 1){
            while (totalSize > 0){
                result[index++] = matrix[startRow][startColumn++];
                totalSize--;
            }
        }

        return result;
    }
}
